import {uSelectDevLogByPage} from '@/api/devLog'
import {exportDevLog, getDevEventType, getDevLogType, uSelectUserDevList} from '@/api/public'
import {CCard} from '@/components/card'
import {ProductFilesItem} from '@/components/others/productFilesItem'
import {DeviceSelect} from '@/components/select/device'
import {CnBoldP, CnBoldSpan, CnNormalP, CnNormalSpan} from '@/components/text'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {getUserId} from '@/libs/auth'
import {baseUrl} from '@/libs/baseUrl'
import {downFile} from '@/libs/toolkit'
import {DatePicker} from 'ant-design-vue'
import dayjs, {Dayjs} from 'dayjs'
import {DLLabel, DLTable, DLTbody, DLTr, DLValue} from './components/filterContent'

type TableColumn = CColumn<DevLog.LogData>

export default defineComponent({
  name: 'dataOverview',
  setup() {
    const {store, route} = useGlobalAPI()

    const state = reactive<{
      tableDatas: DevLog.LogData[]
      tableTotal: number
      currentDevId: number | undefined
      dateRange: Dayjs[]
      pagation: Paging
      tableLoading: boolean
      devList: DeviceData[]
      currentLogType: Dict | null
      currentLogEvent: Dict | null
      logTypeList: Dict[]
      logEventList: Dict[]
    }>({
      currentDevId: undefined,
      dateRange: [],
      tableDatas: [],
      tableTotal: 0,
      pagation: {
        page: 1,
        size: 20
      },
      tableLoading: false,
      devList: [],
      logEventList: [],
      logTypeList: [],
      currentLogEvent: null,
      currentLogType: null
    })

    const tableLoading = ref(false)

    const currentDevId = ref('')

    watch(
      () => state.currentDevId,
      n => {
        console.log(n)

        resetPagination()
        getTableData()
      }
    )
    watch(
      () => state.currentLogType,
      n => {
        resetPagination()
        getTableData()
      }
    )
    watch(
      () => state.currentLogEvent,
      n => {
        resetPagination()
        getTableData()
      }
    )
    watch(
      () => state.dateRange,
      n => {
        resetPagination()
        getTableData()
      }
    )

    const columns: TableColumn[] = [
      {
        title: '设备名称',
        dataIndex: 'devName'
      },
      {
        title: '日志类型',
        dataIndex: 'devLogTypeName'
      },
      {
        title: '日志事件',
        dataIndex: 'devEventTypeName'
      },
      {
        title: '内容',
        dataIndex: 'devLogContent'
      },
      {
        title: '时间',
        dataIndex: 'createTime'
      }
    ]

    function resetPagination() {
      state.pagation.page = 1
      state.pagation.size = 20
    }

    function getTableData() {
      state.tableLoading = true
      tableLoading.value = true
      if (!state.currentDevId) return
      let startDate: string | undefined = undefined
      let endDate: string | undefined = undefined
      if (state.dateRange.length) {
        startDate = state.dateRange[0].format('YYYY-MM-DD 00:00:00')
        endDate = state.dateRange[1].format('YYYY-MM-DD 23:59:59')
      }
      uSelectDevLogByPage({
        devId: state.currentDevId,
        page: state.pagation.page,
        size: state.pagation.size,
        devLogTypeCode: state.currentLogType?.dictCode,
        devEventTypeCode: state.currentLogEvent?.dictCode,
        startDate,
        endDate
      })
        .then(res => {
          state.tableDatas = res.data.list
          state.tableTotal = res.data.total
          nextTick(() => {
            store.dispatch('layoutMain/MAINSCROLLTOTOP')
          })

          state.tableLoading = false
          tableLoading.value = false
        })
        .catch(err => {})
    }

    function getLogType() {
      getDevLogType()
        .then(res => {
          state.logTypeList = res.data
          state.currentLogType = null
          getLogEventType()
        })
        .catch(err => {})
    }

    function getLogEventType() {
      getDevEventType()
        .then(res => {
          state.logEventList = res.data
          state.currentLogEvent = null
        })
        .catch(err => {})
    }

    function handleExportClick() {
      const userId = getUserId()
      if (!userId) return
      const devId = state.currentDevId
      const devLogTypeCode = state.currentLogType?.dictCode || ''
      const devEventTypeCode = state.currentLogEvent?.dictCode || ''
      const startDate = state.dateRange[0]?.format('YYYY-MM-DD 00:00:00')
      const endDate = state.dateRange[1]?.format('YYYY-MM-DD 23:59:59')
      exportDevLog({userId, devId, devLogTypeCode, devEventTypeCode, startDate, endDate})
        .then(res => {
          downFile(res.data, {fileName: '设备日志'})
        })
        .catch(err => {})
    }

    // 当前选择的设备名称
    const currentDevName = ref('')

    onMounted(() => {
      currentDevId.value = route.query.devId
      state.currentDevId = route.query.devId
      currentDevName.value = route.query.devName
      route.query.devId = ''
      getLogType()
    })

    return () => (
      <div class='pb-24'>
        <CnBoldP class='mt-11 text-20'>设备日志</CnBoldP>

        <CnNormalP class='mt-6 mb-20 text-4xText'>查看您设备记录的日志</CnNormalP>

        <ProductFilesItem></ProductFilesItem>

        <CCard title='设备日志' showTitle={false} class='bg-white' canHoverMove={false}>
          <DLTable>
            <DLTbody>
              <DLTr>
                <DLLabel>
                  <CnBoldSpan>日志类型：</CnBoldSpan>
                </DLLabel>
                <DLValue>
                  <a-button
                    size='small'
                    class='flex item-center justify-center shadow-none p-0 h-auto'
                    onClick={() => {
                      state.currentLogType = null
                    }}
                  >
                    <CnNormalSpan
                      class={[
                        'cursor-pointer rounded-2 px-4 py-2',
                        state.currentLogType === null ? 'cSelected' : ''
                      ]}
                    >
                      所有类型
                    </CnNormalSpan>
                  </a-button>
                  {state.logTypeList.map(item => (
                    <a-button
                      size='small'
                      class='flex item-center justify-center shadow-none p-0 h-auto'
                      onClick={() => {
                        state.currentLogType = item
                      }}
                    >
                      <CnNormalSpan
                        class={[
                          'cursor-pointer rounded-2 px-4 py-2',
                          state.currentLogType?.dictCode === item.dictCode ? 'cSelected' : ''
                        ]}
                      >
                        {item.dictName}
                      </CnNormalSpan>
                    </a-button>
                  ))}
                </DLValue>
              </DLTr>
              <DLTr>
                <DLLabel>
                  <CnBoldSpan>日志事件：</CnBoldSpan>
                </DLLabel>
                <DLValue>
                  <a-button
                    size='small'
                    class='flex item-center justify-center shadow-none p-0 h-auto'
                    onClick={() => {
                      state.currentLogEvent = null
                    }}
                  >
                    <CnNormalSpan
                      class={[
                        'cursor-pointer rounded-2 px-4 py-2',
                        state.currentLogEvent === null ? 'cSelected' : ''
                      ]}
                    >
                      所有类型
                    </CnNormalSpan>
                  </a-button>
                  {state.logEventList.map(item => (
                    <a-button
                      size='small'
                      class='flex item-center justify-center shadow-none p-0 h-auto'
                      onClick={() => {
                        state.currentLogEvent = item
                      }}
                    >
                      <CnNormalSpan
                        class={[
                          'cursor-pointer rounded-2 px-4 py-2',
                          state.currentLogEvent?.dictCode === item.dictCode ? 'cSelected' : ''
                        ]}
                      >
                        {item.dictName}
                      </CnNormalSpan>
                    </a-button>
                  ))}
                </DLValue>
              </DLTr>
              <DLTr>
                <DLLabel>
                  <CnBoldSpan>选择设备：</CnBoldSpan>
                </DLLabel>
                <DLValue>
                  <DeviceSelect
                    class='w-288'
                    v-model={[state.currentDevId, 'value']}
                    isDevId={currentDevId.value == '' ? false : true}
                    lazy={false}
                    currentName={currentDevName.value}
                  ></DeviceSelect>
                </DLValue>
              </DLTr>
              <DLTr>
                <DLLabel>
                  <CnBoldSpan>选择时间：</CnBoldSpan>
                </DLLabel>
                <DLValue>
                  <a-range-picker
                    v-model={[state.dateRange, 'value']}
                    allowClear={false}
                  ></a-range-picker>
                  <a-button type='primary' onClick={handleExportClick}>
                    导出
                  </a-button>
                </DLValue>
              </DLTr>
            </DLTbody>
          </DLTable>

          <a-table
            id='devLogTable'
            loading={tableLoading.value}
            columns={columns}
            dataSource={state.tableDatas}
            pagination={{
              current: state.pagation.page,
              pageSize: state.pagation.size,
              size: 'small',
              total: state.tableTotal,
              showTotal: (total: number) => `共 ${total} 条`,
              onChange: (page: number, size: number) => {
                console.log(page, size)
                state.pagation.page = page
                state.pagation.size = size
                getTableData()
              }
            }}
          ></a-table>
        </CCard>
      </div>
    )
  }
})
